import { observer } from 'mobx-react'
import React, { useState, useEffect } from 'react'
import type { PopconfirmProps } from 'antd'
import { Layout, Input, List, Button, Popconfirm, Table, Badge, message, Tooltip } from 'antd'
import type { DataNode } from 'antd/es/tree'
import { useNavigate } from 'react-router-dom'
import { getDictList, getDictDetail } from '@/apis/dictMg'
import InfiniteScroll from 'react-infinite-scroll-component';
import './index.less'

const { Sider, Content } = Layout

interface DataType {
  gender: string;
  name: {
    title: string;
    first: string;
    last: string;
  };
  email: string;
  picture: {
    large: string;
    medium: string;
    thumbnail: string;
  };
  nat: string;
}
interface DictType {
  name: string;
  enCode?: string
}
interface TableDataType {
  tagName: string
  typeEncode: string
  value: string
  sort: string
  describe: string
  status: string
  operator: string
  operationTime: string
}
const DictManagement: React.FC = () => {
  const navigate = useNavigate()
  const [filter, setFilter] = useState(0)
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState<DataType[]>([])
  const [dictData, setDictData] = useState<DictType[]>([])
  const [tableData, setTableData] = useState<TableDataType[]>([])
  const [treeSelectKeys, setTreeSelectKeys] = useState<string[]>([])

  const onTreeSelect = (selectedKeys: React.Key[]) => {
    setTreeSelectKeys(selectedKeys as string[])
    // 根据选中的部门 key，去刷新右侧表格数据
  }
  const onSearchDept = (value: string) => {
    // 搜索部门名称
    getDictData()
  }
  // 新增按钮
  const handleCreate = () => {
    navigate('/setting/dictMg/addField')
  }
  const handleEdit = (record: TableDataType) => {
    console.log(record, 'record---');
    navigate('/setting/dictMg/addField', { state: { record } })
  }
  const handleAdd = () => {
    navigate('/setting/dictMg/add')
  }
  const handleRefresh = () => {
    getDictData()
    message.success('完成')
  }
  const confirm: PopconfirmProps['onConfirm'] = (e) => {
    console.log(e)
    message.success('点击确定')
  }
  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e)
    message.error('点击取消')
  }
  const getDictData = async (name: string | void) => {
    try {
      const res = await getDictList({name})
      setDictData(res.data.list)
      getDictDetailFn('')
    } catch (error: any) {
      message.error(error)
    }
  }
  const getDictDetailFn = async (enCode: string | void) => {
    const res = await getDictDetail()
    setTableData(res.data.list)
  }
  const handleSelected = (item: DictType, index: number) => {
    setFilter(index)
    getDictDetailFn(item.enCode ?? "")
  }
  // const loadMoreData = () => {
  //   if (loading) {
  //     return;
  //   }
  //   setLoading(true);
  //   fetch('https://randomuser.me/api/?results=10&inc=name,gender,email,nat,picture&noinfo')
  //     .then((res) => res.json())
  //     .then((body) => {
  //       setData([...data, ...body.results]);
  //       setLoading(false);
  //     })
  //     .catch(() => {
  //       setLoading(false);
  //     });
  // };
  // 页面初始化时获取数据
  useEffect(() => {
    getDictData()
  }, [])
  return (
    <Layout style={{ height: '100%', marginTop: 20 }} className="app-dict-management">
      {/* 左侧侧边栏 */}
      <Sider
        width={300}
        style={{
          background: '#fff',
          padding: '16px',
          borderRight: '1px solid #f0f0f0',
          marginRight: 16
        }}
      >
        <div className="btn-operations">
          <Button type="primary" onClick={handleAdd}>+ 新增</Button>
          <Button onClick={handleRefresh}>刷新缓存</Button>
        </div>
        <Input.Search
          className='custom-input'
          placeholder="请输入字典名称"
          onSearch={onSearchDept}
          style={{ marginBottom: 16 }}
        />
        {/* 部门树 */}
        {/* <Tree
          treeData={treeData}
          onSelect={onTreeSelect}
          defaultExpandAll
        /> */}
        {/* <InfiniteScroll
          dataLength={dictData.length}
          next={loadMoreData}
          hasMore={dictData.length < 10}
          loader={<Skeleton paragraph={{ rows: 1 }} active />}
          endMessage="暂无数据"
          scrollableTarget="scrollableDiv"
        > */}
          <List
            size="small"
            split={false}
            dataSource={dictData}
            className="dict_list"
            renderItem={(item, index) => (
              <List.Item >
                <div
                  className="dict_list_item"
                  style={{ background: filter === index ? '#F2F3F5' : '' }}
                  onClick={() => handleSelected(item, index)}
                >
                  <span>{item.name}</span>
                  <span>{item.enCode}</span>
                </div>
              </List.Item>
            )}
          />
        {/* </InfiniteScroll> */}
      </Sider>

      {/* 右侧主区域 */}
      <Content style={{ padding: '16px', background: '#fff' }}>
        {/* <Divider /> */}
        <div style={{ marginBottom: 24 }}>
          <Button type="primary" onClick={handleCreate}>
            + 新增
          </Button>
        </div>
        <Table
          columns={[
            { title: '标签名', key: 'tagName', dataIndex: 'tagName' },
            { title: '类型编码', key: 'typeEncode', dataIndex: 'typeEncode', ellipsis: true },
            { title: '数值', key: 'value', dataIndex: 'value' },
            { title: '排序', key: 'sort', dataIndex: 'sort' },
            {
              title: '描述',
              key: 'describe',
              dataIndex: 'describe',
              width: 180,
              ellipsis: {
                showTitle: false,
              },
              render: (describe) => (
                <Tooltip placement="topLeft" title={describe}>
                  {describe}
                </Tooltip>
              ),
            },
            {
              title: '状态',
              dataIndex: 'status',
              key: 'status',
              render: (status) => (
                <>
                  <Badge
                    status={['error', 'success'][status] as any}
                    styles={{ indicator: { marginRight: '8px' } }}
                  />
                  {['禁用', '正常'][status]}
                </>
              ),
            },
            { title: '操作人', key: 'operator', dataIndex: 'operator' },
            { title: '操作时间', key: 'operationTime', dataIndex: 'operationTime', width: 180, },
            {
              title: '操作',
              fixed: 'right',
              width: 180,
              align: 'center',
              key: 'operate',
              render: (record: TableDataType) => (
                <div className='btn-group'>
                  <Button type="link" onClick={() => handleEdit(record)}>修改</Button>
                  <Popconfirm
                    title="确定要禁用吗？"
                    onConfirm={confirm}
                    onCancel={cancel}
                    okText="是的"
                    cancelText="取消"
                  >
                    <Button type="link" danger>禁用</Button>
                  </Popconfirm>
                  <Button type="link" danger disabled>删除</Button>
                </div>
              ),
            },
          ]}
          dataSource={tableData}
          tableLayout="fixed"
          scroll={{ x: 1200 }}
        />
      </Content>
    </Layout>
  )
}

export default observer(DictManagement)